package com.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class WebService extends AsyncTask<GeoPoint, String[], String[]>{
    private static final int TIMEOUT_CONEXAO = 20000; // 20 segundos
    private static final int TIMEOUT_SOCKET = 30000; // 30 segundos
    private static final int TAM_MAX_BUFFER = 10240; // 10Kbytes
    private String url;
    Context mContext;
    OverlayItem destItem;
    
    GeoPoint pointUser;
	GeoPoint pointDest;
    
    public WebService(Context cont_, OverlayItem over) {
    	mContext= cont_;
    	destItem = over;
    }

	
	protected String[] doInBackground(GeoPoint... points) {
		String parserbuilder = "";
        
        try{
            HttpParams httpParameters = new BasicHttpParams();
            
            // Configura o timeout da conexão em milisegundos até que a conexão
            // seja estabelecida
            HttpConnectionParams.setConnectionTimeout(httpParameters, 
                    TIMEOUT_CONEXAO);
            
            // Configura o timeout do socket em milisegundos do tempo 
            // que será utilizado para aguardar os dados
            HttpConnectionParams.setSoTimeout(httpParameters, 
                    TIMEOUT_SOCKET);   
            
            HttpClient httpclient = new DefaultHttpClient(httpParameters);
            GeoPoint origem =  points[0];
            GeoPoint destino = points[1];
            String origem_coord = String.valueOf(origem.getLatitudeE6() / 1E6) + "," + String.valueOf(origem.getLongitudeE6() / 1E6);
            String dest_coord = String.valueOf(destino.getLatitudeE6() / 1E6) + "," + String.valueOf(destino.getLongitudeE6() / 1E6);
            HttpPost httppost = new HttpPost("http://maps.googleapis.com/maps/api/directions/json?origin="+ origem_coord + "&destination=" + dest_coord + "&sensor=false" + "&mode=walking");
    
            HttpResponse response = httpclient.execute(httppost);
            
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(),
                            "UTF-8"), TAM_MAX_BUFFER);
            
            StringBuilder builder = new StringBuilder();
            
            for (String line = null ; (line = reader.readLine())!= null;) {
                builder.append(line).append("\n");
            }
            
            parserbuilder = builder.toString();
            
        }catch(ClientProtocolException e){
            Log.e("WebService", e.toString());
        }
        catch(IOException e){
            Log.e("WebService", e.toString());
        }
        
        String[] resultSet = null;
        try {
			resultSet =  parseJson(parserbuilder);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
        return resultSet;
	}
	
	protected String[] parseJson(String json) throws JSONException{
		
		String[] result = new String[5];
		
		JSONObject job = new JSONObject(json);
		
		JSONArray legsArray = job.getJSONArray("routes").getJSONObject(0).getJSONArray("legs");
		
		String suaLocalizacaolat = legsArray.getJSONObject(0).getJSONObject("start_location").getString("lat");
		String suaLocalizacaolng = legsArray.getJSONObject(0).getJSONObject("start_location").getString("lng");
		String descricaoSuaLocalizacao = legsArray.getJSONObject(0).getString("start_address");
		
		String destLocalizacaolat = legsArray.getJSONObject(0).getJSONObject("end_location").getString("lat");
		String destLocalizacaolng = legsArray.getJSONObject(0).getJSONObject("end_location").getString("lng");
		String descricaoDestLocalizacao = legsArray.getJSONObject(0).getString("end_address");
		
		String tempoCaminhada = legsArray.getJSONObject(0).getJSONObject("duration").getString("text");
		
		
		result[0] = suaLocalizacaolat +"\n"+ suaLocalizacaolng;
		result[1] = descricaoSuaLocalizacao;
		result[2] = destLocalizacaolat + "\n" + destLocalizacaolng;
		result[3] = descricaoDestLocalizacao;
		
		result[4] = tempoCaminhada;
		
		return result;
		
	}
	
	protected void onPostExecute(String[] result) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
		  dialog.setTitle(destItem.getTitle());
		  
		  dialog.setMessage("Sua localização: " + result[0] + "\n" +
				  "Descricao: "+ result[1] +"\n---------------------\n"+ "\nDestino: \n" + result[2] +
				  "\nDescricao: "+ result[3] +"\n---------------------\n"+
				  "\nTempo de Caminhada: " + result[4]);
		 
		  dialog.show();
		  
    }
}